<%--
  Created by IntelliJ IDEA.
  User: 29688
  Date: 2021/4/1
  Time: 12:50
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta charset="utf-8">
    <title>书籍管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../../layui-v2.5.7/layui/css/layui.css" media="all">
    <script src="../../../layui-v2.5.7/layui/layui.js" charset="utf-8"></script>
    <script src="../../../js/jquery.js"></script>
</head>
<body>

<table class="layui-hide" id="test" lay-filter="test">
</table>
<script type="text/html" id="toolbarDemo">
    <div>
        <button type="button" class="layui-btn layui-btn-sm" lay-event="settleAccounts">
            <i class="layui-icon">&#xe698;</i>去结算
        </button>
        <button type="button" class="layui-btn layui-btn-sm" lay-event="delSelect">
            <i class="layui-icon">&#xe640;</i> 删除
        </button>
        <button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>
    </div>
</script>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">保存调整</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script>
    layui.use(['table', 'layer', 'slider'],
        function () {
            var table = layui.table;
            var layer = layui.layer;
            table.render({
                elem: '#test'
                , url: '/user/chart/selectAll?uid=' +${sessionScope.user.uid}
                , toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
                , title: '用户数据表'
                , cols: [[
                    /*设置序号*/
                    {type: 'numbers', fixed: 'left', title: "id"},
                    {type: 'checkbox', fixed: 'left'}
                    , {field: 'bid', title: 'bid', width: 80, fixed: 'left', hide: true}
                    , {field: 'uid', title: 'uid', width: 80, fixed: 'left', hide: true}
                    , {field: 'bname', title: '书名', width: 160, edit: 'text', sort: true}
                    , {
                        field: 'price', title: '单价', width: 150, text: '未绑定', edit: 'text', sort: true
                    }
                    , {field: 'description', title: '描述', width: 200, edit: 'text'}
                    , {field: 'count', title: '数量', width: 100, sort: true, edit: 'number'}
                    , {field: 'bcount', title: '库存', width: 100, sort: true}
                    , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 150}
                ]]
                , page: true,
                skin: 'row',
                even: 'true',
                id: 'bookTable'
            });

            //头工具栏事件
            table.on('toolbar(test)', function (obj) {
                var checkStatus = table.checkStatus(obj.config.id);
                switch (obj.event) {
                    case 'getCheckData':
                        var data = checkStatus.data;
                        layer.alert(JSON.stringify(data));
                        break;
                    case 'delSelect':
                        layer.confirm('真的删除所有选中行？', {icon: 3, title: '询问'}, function () {
                            var data = checkStatus.data;
                            if (data.length > 0) {
                                /*后端删除*/
                                var ids = []
                                for (let i = 0; i < data.length; i++) {
                                    ids.push(data[i].bid)
                                }
                                console.log(ids);
                                /*前端删除*/
                                layer.confirm('确定删除选中' + data.length + '条数据？', {
                                    icon: 3,
                                    title: '提示信息'
                                }, function (index) {
                                    //layui中找到CheckBox所在的行，并遍历找到行的顺序
                                    $("div.layui-table-body table tbody input[name='layTableCheckbox']:checked").each(function () { // 遍历选中的checkbox
                                        n = $(this).parents("tbody tr").index();  // 获取checkbox所在行的顺序
                                        //移除行
                                        $("div.layui-table-body table tbody ").find("tr:eq(" + n + ")").remove();
                                        //如果是全选移除，就将全选CheckBox还原为未选中状态
                                        $("div.layui-table-header table thead div.layui-unselect.layui-form-checkbox").removeClass("layui-form-checked");
                                    });
                                    deleteByIds(ids);
                                    layer.close(index);
                                    layer.msg("删除成功！")
                                })
                            } else {
                                layer.msg("请选择需要删除的行");
                            }
                        });
                        break;
                    case 'settleAccounts':
                        layer.confirm('结算所有选中行？', {icon: 3, title: '询问'}, function (index) {
                            var data = checkStatus.data;
                            /*获取对应的书籍id*/
                            layer.close(index)
                            if (data.length > 0) {
                                var ids = []
                                for (let i = 0; i < data.length; i++) {
                                    ids.push(data[i].bid)
                                }
                                console.log(ids);
                                var result=sesettleAccounts(ids);
                                /*前端删除*/
                                layer.confirm('确定', {
                                    type:1,
                                    title: '结算选中' + data.length + '类书籍,共计' + result+ '元',
                                    content:'<img src="/img/account.jpg" style="width: 260px;height: 260px;"/>',
                                    area:['357px','357px'],
                                    offset:"35px"
                                }, function (index) {
                                    //layui中找到CheckBox所在的行，并遍历找到行的顺序
                                    $("div.layui-table-body table tbody input[name='layTableCheckbox']:checked").each(function () { // 遍历选中的checkbox
                                        n = $(this).parents("tbody tr").index();  // 获取checkbox所在行的顺序
                                        //移除行
                                        $("div.layui-table-body table tbody ").find("tr:eq(" + n + ")").remove();
                                        //如果是全选移除，就将全选CheckBox还原为未选中状态
                                        $("div.layui-table-header table thead div.layui-unselect.layui-form-checkbox").removeClass("layui-form-checked");
                                    });

                                    addBooksToOrder(ids);

                                    layer.close(index);
                                })
                            } else {
                                layer.msg("请选择需要结算的行");
                            }

                        });
                }

            });
            /*删除书籍的方法*/
            function deleteBooks(bid, uid) {
                $.ajax({
                    url: "/user/chart/deleteById?bid=" + bid + "&uid=" + uid, function(data) {
                        console.log(data)
                    }
                })
            }
            /*删除书籍的方法*/
            function addBooksToOrder(ids) {
                $.ajax({
                    data: {"ids": ids, "uid":${sessionScope.user.uid}},
                    url: "/user/chart/createOrderById?",
                    traditional: true,
                    success:function(data) {
                        console.log(data)
                    }
                })
            }

            /*批量删除的方法*/
            function deleteByIds(ids) {
                $.ajax({
                    data: {"ids": ids, "uid":${sessionScope.user.uid}},
                    url: "/user/chart/deleteByIds",
                    dataType: 'json',
                    traditional: true,

                })
            }

            /**
             * 获取结算金额的方法
             * @param ids
             * @returns {number}
             */
            function sesettleAccounts(ids){
                var result =0;
                $.ajax({
                    type: "post",
                    traditional: true,
                    async:false,/*设置为同步请求，防止数据读不到*/
                    url: "/user/chart/settleAccount",
                    data: {"ids": ids, "uid":${sessionScope.user.uid}},
                    success: function (data) {
                        result=data
                    }
                })
                return result;
            }
            //监听行工具事件
            table.on('tool(test)', function (obj) {
                var data = obj.data;
                if (obj.event === 'del') {
                    layer.confirm('真的删除行么', function (index) {
                        obj.del();
                        layer.close(index);
                        deleteBooks(obj.data.bid, obj.data.uid)
                    });
                } else if (obj.event === 'edit') {
                    if (obj.data.count > obj.data.bcount) {
                        layer.msg("超出库存数量!")
                    } else {
                        $.ajax({
                            type: "post",
                            traditional: true,
                            url: '/user/chart/setCount',
                            data: {"uid":${sessionScope.user.uid}, "bid": obj.data.bid, "count": obj.data.count},
                            success: function (data) {
                                if (data > 0) {
                                    layer.msg("修改成功!")
                                }
                            }
                        })
                    }
                }
            });

        });

</script>

</body>
</html>

